<template>
  <div class="user-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>用户管理</h1>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增用户
      </el-button>
    </div>

    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="用户类型">
          <el-select v-model="searchForm.user_type" placeholder="请选择用户类型" clearable>
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户表格 -->
    <el-card>
      <el-table :data="userList" v-loading="loading" border>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="phone_number" label="手机号" min-width="120" />
        <el-table-column prop="user_type" label="用户类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.user_type === 'admin' ? 'danger' : 'success'">
              {{ row.user_type === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="is_active" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="date_joined" label="注册时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.date_joined) }}
        </template>
      </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="row.is_active ? 'warning' : 'success'"
              @click="handleToggleStatus(row)"
            >
              {{ row.is_active ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(row)"
              :disabled="row.user_type === 'admin'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :before-close="handleClose"
    >
      <el-form 
        ref="userFormRef" 
        :model="userForm" 
        :rules="userRules" 
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone_number">
          <el-input v-model="userForm.phone_number" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="用户类型" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择用户类型" style="width: 100%">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="isAdd">
          <el-input v-model="userForm.password" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { userApi } from '@/api/user'
import type { UserInfo, CreateAdminParams } from '@/types/user'
import { formatDateTime } from '@/utils'

// 定义UserForm类型
interface UserForm extends Partial<CreateAdminParams> {
  role?: 'admin' | 'user'
  phone_number?: string
}

const loading = ref(false)
const dialogVisible = ref(false)
const isAdd = ref(true)
const userFormRef = ref()

const searchForm = reactive({
  username: '',
  user_type: ''
})

const userForm = reactive<UserForm>({
  username: '',
  email: '',
  phone_number: '',
  password: '',
  role: 'user'
})

const userList = ref<UserInfo[]>([])

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const userRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone_number: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

import { computed } from 'vue'

const dialogTitle = computed(() => isAdd.value ? '新增用户' : '编辑用户')

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      page_size: pagination.size,
      username: searchForm.username || undefined,
      user_type: searchForm.user_type || undefined
    }
    const response = await userApi.getUserList(params)
    userList.value = response.results || []
    pagination.total = response.count || 0
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchUserList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, { username: '', user_type: '' })
  pagination.current = 1
  fetchUserList()
}

// 新增用户
const handleAdd = () => {
  isAdd.value = true
  Object.assign(userForm, { username: '', email: '', phone_number: '', password: '', role: 'user' })
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row: UserInfo) => {
  isAdd.value = false
  Object.assign(userForm, { 
    id: row.id,
    username: row.username, 
    email: row.email || '', 
    phone_number: row.phone_number || '',
    password: '',
    role: row.user_type
  })
  dialogVisible.value = true
}

// 删除用户
const handleDelete = async (row: UserInfo) => {
  try {
    await ElMessageBox.confirm('确定删除该用户吗？', '提示', {
      type: 'warning'
    })
    
    await userApi.deleteUser(row.id)
    ElMessage.success('删除成功')
    fetchUserList()
  } catch (error) {
    // 用户取消删除
  }
}

// 切换用户状态
const handleToggleStatus = async (row: UserInfo) => {
  try {
    await userApi.updateUserStatus(row.id, !row.is_active)
    ElMessage.success(`${!row.is_active ? '启用' : '禁用'}成功`)
    fetchUserList()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!userFormRef.value) return
  
  try {
    const valid = await userFormRef.value.validate()
    if (!valid) return
    
    if (isAdd.value) {
      // 创建管理员需要完整的用户信息
      const adminData = {
        username: userForm.username || '',
        password: userForm.password || '',
        email: userForm.email || '',
        phone: userForm.phone_number || ''
      }
      await userApi.createAdmin(adminData)
      ElMessage.success('新增成功')
    } else {
      // 更新用户信息
      await userApi.updateProfile({
        username: userForm.username,
        email: userForm.email,
        phone_number: userForm.phone_number
      })
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    fetchUserList()
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  userFormRef.value?.resetFields()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  fetchUserList()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  fetchUserList()
}

onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
